Home |
| Latest | About | Random
# Sieve Answer A short version without user inputs. ```cpp #include #include using namespace std; int main() { int N = 100; int count = 0; string is_prime(N + 1, 't'); for (int p = 2; p <= N; ++p) { if (is_prime.at(p) == 't') { cout << p << ' '; count++; } for (int j = p*p; j <= N; j+=p) { is_prime.at(j) = 'f'; } } cout << endl << "There are " << count << " primes no greater than " << N; return 0; } ``` One with user inputs, you can easily add this! ```cpp #include #include using namespace std; int main() { unsigned int N; char yn; cout << "I will find primes <= N for you!\n"; cout << "Give me an N (don't go too crazy): \n"; cin >> N; cout << "Do you wish to see them all (y/n)?\n"; cin >> yn; unsigned int num_primes = 0; string is_prime(N+1, 't'); for(size_t p = 2; p <= N; p++){ if (is_prime[p] == 't'){ if (yn == 'y') { cout << p << ' '; } ++num_primes; for (size_t j = p * p; j <= N; j += p){ is_prime[j] = 'f'; } } } cout << endl; cout << "There are " << num_primes << " primes <= " << N ; return 0; } ```